package com.john.seckill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.john.seckill.pojo.Order;
import com.john.seckill.pojo.SeckillOrder;
import com.john.seckill.pojo.User;
import com.john.seckill.service.IGoodsService;
import com.john.seckill.service.IOrderService;
import com.john.seckill.service.ISeckillOrderService;
import com.john.seckill.vo.GoodsVo;
import com.john.seckill.vo.ResultBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 秒杀
 * 日期 2021/5/21 15:53
 * 创建者：john driver
 */
@Controller
@RequestMapping("/seckill")
@Slf4j
public class SecKillController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderService orderService;
    @RequestMapping("/doSecKill")
    public String doSecKill(Model model, User user,Long goodsId){
        log.info(String.valueOf(user));
        if(user == null){
            return "login";
        }
        model.addAttribute("user",user);
        final GoodsVo goods = goodsService.findGoodsVoByGoodId(goodsId);
        //判断库存
        if(goods.getStockCount()<1){
            model.addAttribute("errmsg", ResultBeanEnum.EMPTY_STOCK.getMessage());
            return "secKillFail";
        }
        //判断是否重复抢购
        final SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));
        if(seckillOrder!=null){
            model.addAttribute("errmsg",ResultBeanEnum.REPEATE_ERROR.getMessage());
            return "secKillFail";
        }
        //生成订单
        Order order = orderService.seckill(user,goods);
        model.addAttribute("order",order);
        model.addAttribute("goods",goods);
        return "orderDetail";
    }
}
